package com.pms.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.pms.controller.BaseController;
import com.pms.exception.R;
import com.pms.service.tsdb.IIotDeviceService;
import com.pms.service.tsdb.ITsdbService;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * 聚合函数类型{1-求平均数，2-总记录数，3-求总和,4-求相邻值的差,5/6-求最大/小值,7/8-求倍数/除数,9/10-求第一个/最后一个值}
 */
@RestController
@Api(value = "设备管理Api接口", description = "设备管理Api接口")
@RequestMapping(value = "iotDevice", method = RequestMethod.POST)
public class IotDeviceApi extends BaseController {
    @Autowired
    IIotDeviceService iotDeviceService;

    @ApiOperation(value = "创建单个设备")
    @RequestMapping(value = "/createMydevice", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "description", value = "设备描述", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "schemaId", value = "设备模板id", required = true, dataType = "string", paramType = "form"),
    })
    public R createMydevice(Integer address,String deviceName, String description, String schemaId) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        if (StringUtils.isBlank(description)) {
            return R.error(400, "设备描述不能为空");
        }
        if (StringUtils.isBlank(schemaId)) {
            return R.error(400, "设备模板id不能为空");
        }
        JSONObject paramJson = new JSONObject();
        paramJson.put("deviceName", deviceName);
        paramJson.put("description", description);
        paramJson.put("schemaId", schemaId);
        JSONObject dataJson = iotDeviceService.createMydevice(address,paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "删除设备,根据设备名称删除")
    @RequestMapping(value = "/delDevice", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称,多个以,分开", required = true, dataType = "string", paramType = "form"),
    })
    public R delDevice(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject paramJson = new JSONObject();
        paramJson.put("devices", deviceName.split(","));
        JSONObject dataJson = iotDeviceService.delDevice(address,paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "获取设备属性")
    @RequestMapping(value = "/readDeviceProfile", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R readDeviceProfile(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject dataJson = iotDeviceService.readDeviceProfile(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "获取设备Profile和模型合并后的View")
    @RequestMapping(value = "/readDeviceView", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R readDeviceView(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject dataJson = iotDeviceService.readDeviceView(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "获取设备影子列表")
    @RequestMapping(value = "/readDevicePage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "favourite", value = "收藏,1-true,2-false,3-all,默认all", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "value", value = "查询属性名对应的值，默认全量", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "查询属性名，默认全量", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "order", value = "排序规则(1-asc(默认)/2-desc)", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "orderBy", value = "排序字段(1-name(默认)/2-createTime/3-lastActiveTime)", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "查询页码，默认1", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "查询数量，默认10", required = false, dataType = "int", paramType = "form"),
    })
    public R readDevicePage(Integer address,String orderBy, String order, Integer pageNo, Integer pageSize, String name, String value, String favourite) {
        JSONObject paramJson = new JSONObject();
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        paramJson.put("pageNo", pageNo);
        paramJson.put("pageSize", pageSize);
        if (StringUtils.isNotBlank(order)) {
            if (order.equals("2") || order.equals("desc")) {
                order = "desc";
            } else {
                order = "asc";
            }
            paramJson.put("order", order);
        }
        if (StringUtils.isNotBlank(orderBy)) {
            if (orderBy.equals("2") || orderBy.equals("createTime")) {
                orderBy = "createTime";
            } else if (orderBy.equals("3") || orderBy.equals("lastActiveTime")) {
                orderBy = "lastActiveTime";
            }
            {
                orderBy = "name";
            }
            paramJson.put("orderBy", orderBy);
        }
        if (StringUtils.isNotBlank(favourite)) {
            if (favourite.equals("1") || favourite.equals("true")) {
                favourite = "true";
            } else if (favourite.equals("2") || favourite.equals("false")) {
                favourite = "false";
            }
            {
                favourite = "all";
            }
            paramJson.put("favourite", favourite);
        }
        if (StringUtils.isNotBlank(name)) {
            paramJson.put("name", name);
        }
        if (StringUtils.isNotBlank(value)) {
            paramJson.put("value", value);
        }
        JSONObject dataJson = iotDeviceService.readDevicePage(address,paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "获取设备接入详情")
    @RequestMapping(value = "/readDeviceAccessDetail", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R readDeviceAccessDetail(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject dataJson = iotDeviceService.readDeviceAccessDetail(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "更新设备密钥")
    @RequestMapping(value = "/updateDeviceSecretKey", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
    })
    public R updateDeviceSecretKey(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject dataJson = iotDeviceService.updateDeviceSecretKey(address,deviceName);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "更新设备属性，未完成")
    @RequestMapping(value = "/updateDeviceProfile", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "deviceJsonStr", value = "json对象转换的字符串,eg:{\"desired\":{\"light\": \"red\"},\"reported\": {\"light\": \"green\"}}", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "attributesJsonStr", value = "json对象转换的字符串,eg:{\"region\":\"Shanghai\"}", required = false, dataType = "string", paramType = "form"),
    })
    public R updateDeviceProfile(Integer address,String deviceName, String deviceJsonStr, String attributesJsonStr) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject paramJson = new JSONObject();
        try {
            if (StringUtils.isNotBlank(deviceJsonStr)) {
                JSONObject deviceJson = JSONObject.parseObject(deviceJsonStr);
                paramJson.put("device", deviceJson);
            }
            if (StringUtils.isNotBlank(attributesJsonStr)) {
                JSONObject attributesJson = JSONObject.parseObject(attributesJsonStr);
                paramJson.put("attributes", attributesJson);
            }
        } catch (JSONException ex) {
            return R.error(400, "参数错误，json解析异常");
        }
        JSONObject dataJson = iotDeviceService.updateDeviceProfile(address,deviceName, paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "更新设备view信息")
    @RequestMapping(value = "/updateDeviceSingleView", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "deviceJsonStr", value = "json对象转换的字符串,eg:{\"desired\":{\"light\": \"red\"},\"reported\": {\"light\": \"green\"}}", required = true, dataType = "string", paramType = "form"),
    })
    public R updateDeviceSingleView(Integer address,String deviceName, String deviceJsonStr) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject paramJson = new JSONObject();
        try {
            JSONObject deviceJson = JSONObject.parseObject(deviceJsonStr);
            paramJson.put("desired", deviceJson.get("desired"));
            paramJson.put("reported", deviceJson.get("reported"));
        } catch (JSONException ex) {
            return R.error(400, "参数错误，json解析异常");
        }
        JSONObject dataJson = iotDeviceService.updateDeviceSingleView(address,deviceName, paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "更新设备注册表信息")
    @RequestMapping(value = "/updateDeviceSingleRegistry", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "设备名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "description", value = "需要更新的设备描述", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "schemaId", value = "需要更换的模板Id", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "favourite", value = "是否需要收藏(1-是，2-否(默认))", required = false, dataType = "string", paramType = "form"),
    })
    public R updateDeviceSingleRegistry(Integer address,String deviceName, String description, String schemaId, String favourite) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject paramJson = new JSONObject();
        if (StringUtils.isNotBlank(description)) {
            paramJson.put("description", description);
        }
        if (StringUtils.isNotBlank(favourite)) {
            if (favourite.equals("1") || favourite.equals("true")) {
                paramJson.put("favourite", true);
            } else {
                paramJson.put("favourite", false);
            }
        }
        if (StringUtils.isNotBlank(schemaId)) {
            paramJson.put("schemaId", schemaId);
        }
        JSONObject dataJson = iotDeviceService.updateDeviceSingleRegistry(address,deviceName, paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "重置设备影子")
    @RequestMapping(value = "/resetDevice", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "deviceName", value = "需重置的设备名称,多个以,分开", required = true, dataType = "string", paramType = "form"),
    })
    public R resetDevice(Integer address,String deviceName) {
        if (StringUtils.isBlank(deviceName)) {
            return R.error(400, "设备名称不能为空");
        }
        JSONObject paramJson = new JSONObject();
        paramJson.put("devices", deviceName.split(","));
        JSONObject dataJson = iotDeviceService.resetDevice(address,paramJson);
        return R.ok().put("code", dataJson.get("iotHttpCode")).put("data", dataJson);
    }
}
